<template>
  <div class="app-container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input v-model="formInline.strRolename" placeholder="角色名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" icon="el-icon-edit" @click="addAppRole()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      :title="dialogTitleType"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item prop="strRolename" label="角色名称">
              <el-input v-model="form.strRolename" placeholder="角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="iOrgsysnum" label="所属机构">
              <el-cascader
                v-model="form.iOrgsysnum"
                :show-all-levels="false"
                :options="optionslist"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
                @change="queryProduct"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="职责" prop="strDetail" label-width="100">
          <el-input v-model="form.strDetail" type="textarea" />
        </el-form-item>
        <el-form-item prop="product" label="角色权限">
          <el-cascader
            v-model="form.product"
            :options="products"
            :props="{
              expandTrigger: 'hover',
              value: 'prodctNum',
              label: 'prodctName',
              children: 'product',
              multiple: true
            }"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="succ('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改角色" :visible.sync="dialogFormUpdate">
      <el-form ref="updateform" :model="updateform" :rules="ruless" label-width="100">
        <el-row :gutter="40">
          <el-col :span="10">
            <el-form-item prop="strRolename" label="角色名称">
              <el-input v-model="updateform.strRolename" placeholder="角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="iOrgsysnum" label="所属机构">
              <el-cascader
                v-model="updateform.iOrgsysnum"
                :show-all-levels="false"
                :options="optionslist"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
                @change="queryProduct"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="职责" prop="strDetail" label-width="100">
              <el-input v-model="updateform.strDetail" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="product" label="角色权限">
              <el-cascader
                v-model="updateform.product"
                :options="products"
                :props="{
              expandTrigger: 'hover',
              value: 'prodctNum',
              label: 'prodctName',
              children: 'product',
              multiple: true
            }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUpdate = false">取 消</el-button>
        <el-button type="primary" @click="updatesucc('updateform')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="角色详情" :visible.sync="dialogFormDatil">
      <el-form ref="formDatil" :model="formDatil" label-width="100">
        <el-row :gutter="40">
          <el-col :span="10">
            <el-form-item label="角色名称">
              <el-input v-model="formDatil.strRolename" placeholder="角色名称" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属机构">
              <el-cascader
                v-model="formDatil.iOrgsysnum"
                :show-all-levels="false"
                :options="optionslist"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
                @change="queryProduct"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="职责" prop="strDetail" label-width="100">
          <el-input v-model="formDatil.strDetail" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDatil = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="strRolenum" label="角色编号" />
      <el-table-column prop="strRolename" label="角色名称" />
      <el-table-column prop="strOrgName" label="所属机构" />
      <el-table-column prop="strDetail" label="职责" />
      <el-table-column prop="productName" label="角色权限" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="240">
        <template slot-scope="{ row }">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button type="info" size="mini" @click="selectRole(row)">查看</el-button>
            <el-button type="primary" size="mini" @click="openupdate(row)">修改</el-button>
            <el-button type="danger" size="mini" @click="DeleteRole(row)">删除</el-button>
          </template>
          <template v-else>
            <el-button type="info" size="mini" @click="selectRole(row)">查看</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="queryRoleInfoByTerminal"
    />
  </div>
</template>
<script>
import {
  deleteRole,
  queryProduct,
  getList,
  addRoleInfo,
  updRoleInfo,
  listRoleProduct,
  // eslint-disable-next-line no-unused-vars
  queryRoleInfoByTerminal
} from '@/api/system/system'
import { getOrglists } from '../../api/addTag'
import Pagination from '@/components/Pagination'
import { validatestrRolename, validatil } from '../../utils/validateForm'
import { mapGetters } from 'vuex'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      formInline: {
        strRolename: ''
      },
      form: {
        strRolename: '',
        iOrgsysnum: '',
        strDetail: ''
      },
      updateform: {
        strRolename: '',
        iOrgsysnum: '',
        strDetail: '',
        product: []
      },
      formDatil: {
        strRolename: '',
        iOrgsysnum: '',
        strDetail: ''
      },
      tableData: [],
      rules: {
        strRolename: [
          { required: true, validator: validatestrRolename, trigger: 'blur' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strDetail: [{ required: true, validator: validatil, trigger: 'blur' }],
        product: [{ required: true, message: '请选择权限', trigger: 'change' }]
      },
      ruless: {
        strRolename: [
          { required: true, validator: validatestrRolename, trigger: 'blur' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strDetail: [{ required: true, validator: validatil, trigger: 'blur' }],
        product: [{ required: true, message: '请选择权限', trigger: 'change' }]
      },
      dialogFormVisible: false,
      dialogFormDatil: false,
      dialogFormUpdate: false,
      dialogTitleType: '新增角色',
      options: [],
      optionslist: [],
      data: [],
      products: [],
      prodctName: [],
      defaultProps: {
        children: 'product',
        label: 'prodctName'
      },
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper'
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum'])
  },
  created() {
    this.queryRoleInfoByTerminal()
  },
  methods: {
    onSubmit() {
      this.queryRoleInfoByTerminal()
    },
    DeleteRole(row) {
      this.$confirm(
        '此操作将永久删除角色：' + row.strRolename + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteRole({ id: row.id }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.queryRoleInfoByTerminal()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    queryRoleInfoByTerminal() {
      getList({
        rows: this.pagenum,
        strRolename: this.formInline.strRolename,
        iType: 1,
        iOrgsysnum: this.$store.getters.iOrgsysnum
      }).then(res => {
        this.tableData = res && res.data
        this.total = !res ? 0 : res.total
      })
      getOrglists({ iOrgnum: this.$store.getters.iOrgsysnum }).then(res => {
        if (this.$store.getters.iOrgsysnum === -1) {
          this.optionslist = res && res.data
        } else {
          this.optionslist.push(res.data)
        }
      })
    },
    openupdate(row) {
      this.updateform.strRolename = row.strRolename
      this.updateform.iOrgsysnum = row.iOrgsysnum + ''
      this.updateform.strDetail = row.strDetail
      this.updateform.id = row.id
      this.updateform.iRolesysnum = row.iRolesysnum
      queryProduct({ iOrgsysnum: this.updateform.iOrgsysnum }).then(res => {
        this.products = res.data
      })
      listRoleProduct({ iRolesysnum: this.updateform.iRolesysnum }).then(
        res => {
          //  this.updateform.product=[[9,180000029],[9,180000027]];
          const product = []
          res.data.map(item => {
            product.push(parseInt(item.Type) + ',' + parseInt(item.ProductNum))
          })
          console.log(product)
          this.updateform.product = product
        }
      )
      this.$nextTick(() => {
        this.$refs['updateform'].resetFields() // this.$refs.adduserform.resetFields();
      })
      this.dialogFormUpdate = true
    },
    selectRole(row) {
      this.formDatil.strRolename = row.strRolename
      this.formDatil.iOrgsysnum = row.iOrgsysnum + ''
      this.formDatil.strDetail = row.strDetail
      this.dialogFormDatil = true
    },
    addAppRole() {
      this.form.strRolename = ''
      this.form.iOrgsysnum = ''
      this.form.strDetail = ''
      this.products = []
      this.dialogFormVisible = true
    },
    queryProduct(val) {
      const iOrgsysnum = JSON.stringify(val)
      queryProduct({ iOrgsysnum: iOrgsysnum }).then(res => {
        this.products = res.data
      })
    },
    updatesucc(formName) {
      if (!(this.updateform.iOrgsysnum instanceof Array)) {
        let iOrgsysnum = []
        iOrgsysnum.push(this.updateform.iOrgsysnum)
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.updateform.iOrgsysnum = iOrgsysnum[0]
      } else {
        let iOrgsysnum = this.updateform.iOrgsysnum
        iOrgsysnum = iOrgsysnum.splice(-1)
        this.updateform.iOrgsysnum = iOrgsysnum[0]
      }
      this.updateform.iType = 1
      this.updateform.iType = 1
      this.$refs[formName].validate(valid => {
        if (valid) {
          var perms = []
          console.log(this.updateform.product)
          if (this.updateform.product.length === 1) {
            perms.push(this.updateform.product.splice(-1))
          } else if (this.updateform.product.length >= 2) {
            this.updateform.product.map(item => {
              perms.push(item.splice(-1))
            })
          }
          this.updateform.perms = perms.toString()

          updRoleInfo(this.updateform).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.dialogFormUpdate = false
            this.$refs[formName].resetFields()
            this.queryRoleInfoByTerminal()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    succ(formName) {
      if (this.dialogTitleType === '新增角色') {
        var perms = []
        if (!(this.form.iOrgsysnum instanceof Array)) {
          let iOrgsysnum = []
          iOrgsysnum.push(this.form.iOrgsysnum)
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        } else {
          let iOrgsysnum = this.form.iOrgsysnum
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        }
        this.form.product.map(item => {
          perms.push(item.splice(-1))
        })
        this.form.iType = 1
        this.form.perms = perms.toString()
        alert(this.form.perms)
        console.log(this.form.perms)
        this.$refs[formName].validate(valid => {
          if (valid) {
            addRoleInfo(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.dialogFormVisible = false
              this.$refs[formName].resetFields()
              this.queryRoleInfoByTerminal()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
}
</script>
